package com.xexun.gpstracker.receiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.MainActivity;
import com.xexun.gpstracker.baby.activity.ChatActivity;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.pojo.*;
import com.xexun.gpstracker.service.CommunicationService;
import com.xexun.gpstracker.util.CommUtil;
import com.xexun.gpstracker.util.Utils;
import com.xexun.gpstracker.vo.ContType;
import com.xexun.gpstracker.vo.Session;

/**
 * Created by HH
 * Date: 2015/7/17 0017
 * Time: 下午 5:26
 */
public class TrackerReceiver extends BroadcastReceiver {
    private Boolean isPlaying = false;
    public static final int MSG_SEND_FAILED=99;

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent!=null){
            Bundle extras = intent.getExtras();
            String action = extras.getString("action");
            if (Constants.ACTION_NEW_MSG.equals(action)){
                processActionNewMsg(context, intent);
            }else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)){
                if (Utils.isNetworkConnected(context) && CommunicationService.get() != null) {
                    CommunicationService.get().connect();
                }
            }
        }

//        switch (intent.getAction()) {
//            case Constants.ACTION_NEW_MSG:
//                processActionNewMsg(context, intent);
//                break;
//            case ConnectivityManager.CONNECTIVITY_ACTION:
//                if (Utils.isNetworkConnected(context) && CommunicationService.get() != null) {
//                    CommunicationService.get().connect();
//                }
//                break;
//        }
    }

    private void processActionNewMsg(Context context, Intent intent) {
        long id = intent.getLongExtra("id", 0);
        int type = intent.getIntExtra("type", 0);
        if (id == 0) {
            return;
        }
        switch (type) {
            case MSG_SEND_FAILED:
                ChatActivity activity = ChatActivity.getChatActivity();
                if (activity != null) {
                    ChatActivity.ChatHandler handler = activity.getHandler();
                    Message cmsg = Message.obtain(handler, ChatActivity.UPDATE_CHAT_FAILED);
                    cmsg.obj = id;
                    handler.sendMessage(cmsg);
                }
                break;
            case 1:
                AppContext.newChatMsgIds.add(id);
                showNotify(context, id);
                Utils.playSoundAndVibrate(context);
                break;
        }
    }

    private static void showNotify(Context context, Long id) {
        try {
            ChatMsg chatMsg = AppContext.db.findById(ChatMsg.class, id);
            //更新消息界面消息
            AppContext.getEventBus().post(chatMsg, Constants.EVENT_TAG_UNREAD_DATA);
            ManaRelation abstractUser = Session.getInstance().getAbstractUser(chatMsg.getImei());
            String title = null;
            if (abstractUser != null) {
                if (abstractUser instanceof Device) {
                    Device device = (Device) abstractUser;
                    title = CommUtil.toStr(device.getName());
                } else if (abstractUser instanceof Keeper) {
                    Keeper keeper = (Keeper) abstractUser;
                    title = CommUtil.toStr(keeper.getNickName());
                }

            }
            if (CommUtil.isBlank(title)) {
                title = context.getString(R.string.stranger);
                return;
            }
            String cont = Utils.getPrettyDescribe(context, ContType.getType(chatMsg.getType()), chatMsg.getContent(), 20);

            Intent intent = new Intent(context, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            intent.putExtra(Constants.REFRESH_FLAG, true);
            MapEntity mEntity = Session.getInstance().getMapEntityByImei(chatMsg.getImei());
            intent.putExtra("chat", mEntity);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            Notification.Builder builder = new Notification.Builder(context).setAutoCancel(true).setSmallIcon(R.drawable.ic_launcher)
                    .setWhen(System.currentTimeMillis()).setContentTitle(title).setContentText(cont)
                    .setContentIntent(pendingIntent).setLights(0xffff0000, 1000, 2000);
            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notification = builder.getNotification();
            manager.notify(Constants.NOTIFIACTION_ID + 99, notification);

            ChatActivity activity = ChatActivity.getChatActivity();
            if (activity != null) {
                ChatActivity.ChatHandler handler = activity.getHandler();
                Message cmsg = Message.obtain(handler, ChatActivity.UPDATE_CHAT_UI);
                cmsg.obj = intent;
                handler.sendMessage(cmsg);
            }
        } catch (Exception e) {
            Log.e(Constants.TAG, "保存消息失败", e);
        }
    }

    public static void clearNotification(int type) {
        NotificationManager manager = (NotificationManager) AppContext.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(Constants.NOTIFIACTION_ID + type);
    }
}
